import processing.core.*;

public class BlueScreenMatting extends PApplet {
  PImage background, top;
  
  public static void main(String[] args) {
    PApplet.main(new String[] {"BlueScreenMatting"});
  }
  
  public void setup(){
    // naložimo slike
    background = loadImage("background.png");
    top = createMattingImage(loadImage("football.png"), "blue");
    
    size(3*background.width, background.height);

    // narišemo sliki na canvas
    image(background,0,0);
    image(top,background.width,0);
    
    // izvedemo matting na ustrezni barvi
    PImage matted = matting("blue");
    
    // in pridobljeno sliko narišemo na canvas
    image(matted,2*background.width,0);
  }
  
  public void draw(){}
  
  // funkcija, ki nam naredi matting
  public PImage matting(String type){
    
    // naložimo piksle za ozadje in sliko z modrim ozadjem
    background.loadPixels();
    top.loadPixels();
    
    // ustvarimo začasno sliko in naložimo njene piksle
    PImage matted = createImage(background.width,background.height,RGB);
    matted.loadPixels();
    
    // določimo vrednosti za primerjanje glede na tip
    int mRed = 0, mBlue = 0, mGreen = 0;
    if(type == "blue") mBlue = 255;
    if(type == "green") mGreen = 255;
    if(type == "red") mRed = 255;
    
    // sprehodimo se čez piksle slike z modrim zaslonom
    for(int i = 0; i < top.pixels.length; i++){
      
      // preberemo R, G in B vrednosti posameznega piksla
      int blue = (int)blue(top.pixels[i]);
      int red = (int)red(top.pixels[i]);
      int green = (int)green(top.pixels[i]);
      
      // odločimo se glede na vrednosti
      if(blue == mBlue && red == mRed && green == mGreen){
        matted.pixels[i] = background.pixels[i]; // to je ozadje, ne prepišemo
      } else {
        matted.pixels[i] = top.pixels[i]; // to ni ozadje, prepišemo
      }
    }
    
    matted.updatePixels();
    
    return matted;
  }

  public PImage createMattingImage(PImage overlay, String color){
    PImage chromaImage = createImage(background.width,background.height,RGB);
    
    chromaImage.loadPixels();
    overlay.loadPixels();
    
    // we decide the background color
    int bBlue = 0, bGreen = 0, bRed = 0;
    
    if(color == "blue") bBlue = 255;
    if(color == "red") bRed = 255;
    if(color == "green") bGreen = 255;
    
    // we apply the background
    for(int i = 0; i < chromaImage.pixels.length; i++){
      chromaImage.pixels[i] = color(bRed, bGreen, bBlue);
    }
    
    // we figure out the middle of the photo
    int positionX = chromaImage.width/2 - overlay.width/2;
    int positionY = chromaImage.height/2 - overlay.height/2;
    
    chromaImage.blend(overlay, 0, 0, overlay.width, overlay.height, positionX, positionY, overlay.width, overlay.height, BLEND);
    
    chromaImage.updatePixels();
    
    return chromaImage;
  }
}
